module(..., package.seeall)

function new(obj)
	local ui = require("ui")

	local groupKhoiDong = display.newGroup()
	local tapSound = audio.loadSound( "tapsound.wav" )
	local khoidong = audio.loadStream("audios/khoidong.mp3" )
	
	local times 				= 60
	local score 				= 0
	local quesAnswer 			= 0
	local quesAnswerCorrect 	= 0
	
	local scoreText 			= nil
	local quesText 				= nil
	local scoreGroup 			= nil
	local nut					= nil
	
	local groupQuestionStart	= nil
	local groupResult			= nil
	--
	local dataKhoiDong = obj.dataKhoiDong
	---------------------------------------------
	--
	---------------------------------------------
	function dispayAccont()
		
		if fullNameText == nil then
			fullNameText = display.newText(obj.fullname, 112,  122, "Helvetica", 12)
			fullNameText:setTextColor(255, 255, 255)
			fullNameText.x = 112
			fullNameText.align = "center"
			groupKhoiDong:insert( fullNameText )	
		else
			fullNameText.text = "Trần Anh Tuấn"
		end
		
		if quesAllText == nil then
			quesAllText = display.newText("12 câu hỏi", 280,  122, "Helvetica", 12)
			quesAllText:setTextColor(255, 0, 0)
			quesAllText.x = 280
			quesAllText.align = "center"
			groupKhoiDong:insert( quesAllText )	
		else
			quesAllText.text = "Bộ 12 câu"
		end
	end
	---------------------------------------------
	--
	---------------------------------------------
	function slipWords(str, key)
		local k = 1
		local index = 1
		local data = {}
		while index > 0 do
			local i, j = string.find(str, key, k)
			if i == nil then
				data[index] = str:sub(k)
				--print(data[index])
				index = -1
			else
				--print(i .. " - " .. j)
				local si = str:sub(k, i - 1)
				data[index] = si
				--print(data[index])
				k = j + 1
			end
			index = index + 1
		end
		return data
	end
	---------------------------------------------
	--Hien thi cau hoi tu hang nang
	---------------------------------------------
	function showQuestions(contents, answers, answerAB)
		local groupQuestion = nil
		local groupAnswer = display.newGroup()
		
		if groupQuestion == nil then
			groupQuestion = display.newGroup()
			groupQuestion.isVisible = false
			groupKhoiDong:insert(groupQuestion)
			groupQuestion:insert(groupAnswer)
			groupAnswer.isVisible = false
			
			btnBoQua= ui.newMyButton{
				default = "images/btnBoQua.png",
				over = "images/btnBoQuaOver.png",
				onRelease = function(event)
					if groupQuestion and times > 0 then
						groupQuestion.isVisible = false
						--xoa
						cleanGroups(groupQuestion, 0)
						if theTimer then
						   timer.cancel(theTimer)	
						end
						
						--Tra loi sai
						quesAnswer = quesAnswer + 1
						
						showScore()
						
						--Da tra loi het 12 cau hoi nhanh
						if quesAnswer > 12 then
							--Thuc hien thong bao da hoan thanh phan thi
							timer.performWithDelay(2500, function(event)
								displayFinish()
							end, 1)
						else
							--Hien thi cau tiep theo
							timer.performWithDelay(500, function(event)
								--showQuestions("Câu 2: Huế nằm ở khu vực nào sau đây?", "A. Miền Nam   B. Miền Trung", "B")
								showQuestions(dataKhoiDong[quesAnswer].questions, dataKhoiDong[quesAnswer].answers, dataKhoiDong[quesAnswer].answerAB)
							end, 1)
						end
					end
				end
				}
			btnBoQua.x = 280
			btnBoQua.y = 290
			groupAnswer:insert(btnBoQua)	
		end
		
		if groupQuestion.isVisible == false then
			groupQuestion.isVisible = true
			groupQuestion.xScale = 0.2
			groupQuestion.yScale = 0.2
			--Xoa
			if groupQuestion.groupWord ~= nil then
				cleanGroups(groupQuestion.groupWord, 0)
			end
			groupQuestion.groupWord = display.newGroup()
			groupQuestion:insert(groupQuestion.groupWord)
					
			transition.to(groupQuestion, {time=100, xScale = 1, yScale = 1, transition=easing.outExpo,
				onComplete = function(event) 
					--Su kien slide khung hien thi cau hoi da thuc hien xong
					displayText(200, groupQuestion.groupWord, contents, 26, 155, 300, 14, 0, 0, 255)
					
					displayText(500, groupQuestion.groupWord, answers, 26, 220, 300, 14, 0, 0, 255)
				end})
			A = ui.newMyButton{
			default = "images/A.png",
			over = "images/AX.png",
				onRelease = function(event)
					if times > 0 then
						if answerAB == "A" then
							--Tra loi dung
							score = score + 10
							quesAnswerCorrect = quesAnswerCorrect + 1
							quesAnswer = quesAnswer + 1
							showScore()
						else
							--Tra loi sai
							quesAnswer = quesAnswer + 1
							showScore()
						end
						--xoa
						cleanGroups(groupQuestion, 0)
						if theTimer then
						   timer.cancel(theTimer)	
						end
						--Da tra loi het 12 cau hoi nhanh
						if quesAnswer > 12 then
							--Thuc hien thong bao da hoan thanh phan thi
							timer.performWithDelay(2500, function(event)
								displayFinish()
							end, 1)
						else
							--Hien thi cau tiep theo
							timer.performWithDelay(500, function(event)
								--showQuestions("Câu 2: Huế nằm ở khu vực nào sau đây?", "A. Miền Nam   B. Miền Trung", "B")
								showQuestions(dataKhoiDong[quesAnswer].questions, dataKhoiDong[quesAnswer].answers, dataKhoiDong[quesAnswer].answerAB)
							end, 1)
						end
					end
				end
			}
			A.x = 50
			A.y = 290
			groupAnswer:insert(A)	
			
			B = ui.newMyButton{
			default = "images/B.png",
			over = "images/BX.png",
				onRelease = function(event)
					if times > 0 then
						if answerAB == "B" then
							--Tra loi dung
							score = score + 10
							quesAnswerCorrect = quesAnswerCorrect + 1
							quesAnswer = quesAnswer + 1
							showScore()
						else
							--Tra loi sai
							quesAnswer = quesAnswer + 1
							showScore()
						end
						--xoa
						cleanGroups(groupQuestion, 0)
						if theTimer then
						   timer.cancel(theTimer)	
						end
						--Da tra loi het 12 cau hoi nhanh
						if quesAnswer > 12 then
							--Thuc hien thong bao da hoan thanh phan thi
							timer.performWithDelay(2500, function(event)
								displayFinish()
							end, 1)
						else
							--Hien thi cau tiep theo
							timer.performWithDelay(500, function(event)
								--showQuestions("Câu 2: Huế nằm ở khu vực nào sau đây?", "A. Miền Nam   B. Miền Trung", "B")
								showQuestions(dataKhoiDong[quesAnswer].questions, dataKhoiDong[quesAnswer].answers, dataKhoiDong[quesAnswer].answerAB)
							end, 1)
						end
					end
				end
			}
			B.x = 120
			B.y = 290
			groupAnswer:insert(B)	
			
			timer.performWithDelay(500, function(e)
				groupAnswer.isVisible = true
			end, 1)
		end
	end
	---------------------------------------------
	--Hien thi diem so va thoi gian tra loi cau hoi
	---------------------------------------------
	function showScore()
		if scoreGroup == nil then
			scoreGroup = display.newGroup()
			groupKhoiDong:insert(scoreGroup)
		end
		
		if scoreText == nil then
			scoreText = display.newText( "00", 370,  286, "Helvetica", 28)
			scoreText:setTextColor(255, 255, 0)
			scoreText.align = "center"
			scoreGroup:insert( scoreText )	
			
			scoreText.x = 368
			scoreText.y = 286
		else
			if score > 0 then
				scoreText.text = "" .. score
			end
		end
		
		if quesText == nil then
			quesText = display.newText("0/0", 370,  246, "Helvetica", 14)
			quesText:setTextColor(255, 0, 0)
			quesText.align = "center"
			scoreGroup:insert( quesText )	
			
			quesText.x = 370
			quesText.y = 246
		else
			quesText.text = "" .. quesAnswerCorrect .. "/" .. (quesAnswer -1)
		end
		
		if nut == nil then
			nut = display.newImage("images/nut.png")
			scoreGroup:insert( nut )	
			
			nut.x = 374
			nut.y = 40
		end
	end
	---------------------------------------------
	--
	---------------------------------------------
	function displayText(delay, group, str, xx, yy, width, fontSize, r, g, b)
		local words = slipWords(str, ' ')
		local i = 1
		local x = xx
		local y = yy

		timer.performWithDelay(delay, function(event)
			while i < #words + 1 do
				local word = display.newText(words[i], 0, 0, native.systemFontBold, fontSize)
				word:setTextColor(r, g, b)
				group:insert(word)
				
				if x + word.width < (xx + width) then
					xxy = x + word.width/2
					yyy = y
					
					word.x = 480
					word.y = 320
					--Hieu ung bay chu tu goc duoi ben trai
					transition.to(word, {time=100*i, x = xxy, y = yyy})
					
					x = x + word.width  + 3
				else
					y = y + 20
					x = xx
					
					xxy = x + word.width/2
					yyy = y
					
					word.x = 480
					word.y = 320
					--Hieu ung bay chu tu goc duoi ben trai
					transition.to(word, {time=100*i, x = xxy, y = yyy})
					
					x = x + word.width  + 3
				end
				i = i+1
			end
		end, 1)
	end
	---------------------------------------------
	--
	---------------------------------------------
	function displayFinish()
		--Hien thong bao het thoi gian phan thi
		if groupResult == nil then
			groupResult = display.newGroup()
			groupKhoiDong:insert(groupResult)		
			
			bgMessage = display.newImage("images/bgMessage.png")
			bgMessage.x = display.contentWidth/2
			bgMessage.y = display.contentHeight/2
			groupResult:insert(bgMessage)
			
			yy = bgMessage.y - bgMessage.height/2 + 40
			displayText(200, groupResult, "BẠN ĐÃ HOÀN THÀNH KHỞI ĐỘNG", bgMessage.x - bgMessage.width/2 + 26, yy, bgMessage.width - 20, 16, 0, 0, 255)
			
			yy = bgMessage.y - 32
			displayText(500, groupResult, "XIN CHÚC MỪNG BẠN", bgMessage.x - bgMessage.width/2 + 68, yy, bgMessage.width - 20, 18, 0, 0, 255)
			
			yy = bgMessage.y
			displayText(500, groupResult, "ĐÃ DÀNH ĐƯỢC " .. score .. " ĐIỂM", bgMessage.x - bgMessage.width/2 + 58, yy, bgMessage.width - 20, 18, 0, 0, 255)
			
			
			btnDiTiep = ui.newMyButton{
			default = "images/btnDiTiep.png",
			over = "images/btnDiTiepOver.png",
				onRelease = function(event)
					--Tro ve man hinh truoc
					timer.performWithDelay(100, function(event)
						--luu diem so man choi de sang man tiep theo
						obj.score  = score
						director:changeScene("vcnv", obj)
					end, 1)
				end
			}
			btnDiTiep.x = bgMessage.x
			btnDiTiep.y = bgMessage.y + 52
			btnDiTiep.isVisible = false
			groupResult:insert(btnDiTiep)
			
			timer.performWithDelay(1000, function(e)
				btnDiTiep.isVisible = true
				--Luu diem so len server
				timer.performWithDelay(200, submitAccountScore, 1)
			end, 1)
		end
	end
	---------------------------------------------
	--Tinh thoi gian phan thi
	---------------------------------------------
	function begin()
		if times > 0 then
			times = times - 1
			
			k = 190/60
			nut.y = 40 + k*(60 - times)
			
			showScore()
		end
		if times == 0 then
			displayFinish()
		end
	end
	---------------------------------------------
	--
	---------------------------------------------
	function submitAccount()
		local url = "http://" .. serverConnect .. "/server.ashx?action=OLPASTART&email=" .. obj.email .. "&pass=" .. obj.pass
		local xmlTree = xml:doQuery(url)
	end
	---------------------------------------------
	--
	---------------------------------------------
	function submitAccountScore()
		local url = "http://" .. serverConnect .. "/server.ashx?action=OLPAUPSCORE&email=" .. obj.email .. "&score=" .. score .. "&pass=" .. obj.pass
		local xmlTree = xml:doQuery(url)
	end
	---------------------------------------------
	--
	---------------------------------------------
	function start()
		if groupQuestionStart == nil then
			groupQuestionStart = display.newGroup()
			groupKhoiDong:insert(groupQuestionStart)		
			
			bgMessage = display.newImage("images/bgMessage.png")
			bgMessage.x = display.contentWidth/2
			bgMessage.y = display.contentHeight/2
			groupQuestionStart:insert(bgMessage)
			
			yy = bgMessage.y - bgMessage.height/2 + 40
		    displayText(200, groupQuestionStart, "CHÀO MỪNG BẠN ĐẾN VỚI CUỘC THI", bgMessage.x - bgMessage.width/2 + 26, yy, bgMessage.width - 20, 16, 0, 0, 255)
			
			yy = bgMessage.y - 32
			displayText(500, groupQuestionStart, "OLYMPIA TRÊN MOBILE", bgMessage.x - bgMessage.width/2 + 48, yy, bgMessage.width - 20, 20, 0, 0, 255)
			
			btnStart = ui.newMyButton{
			default = "images/btnSanSang.png",
			over = "images/btnSanSangOver.png",
				onRelease = function(event)
					timer.performWithDelay(2000, submitAccount, 1)
					--xoa giao dien thong bao
					cleanGroups(groupQuestionStart, 0)
					--dat thoi gian phan thi la 60 giay
					times = 60
					--bat dau tinh thoi gian phan thi
					timer.performWithDelay(1000, begin, 61)
					
					quesAnswer = 1
					showQuestions(dataKhoiDong[quesAnswer].questions, dataKhoiDong[quesAnswer].answers, dataKhoiDong[quesAnswer].answerAB)
				end
			}
			btnStart.x = bgMessage.x + 48
			btnStart.y = bgMessage.y + 52
			btnStart.isVisible = false
			groupQuestionStart:insert(btnStart)
			
			btnMenu = ui.newMyButton{
			default = "images/btnTroLai.png",
			over = "images/btnTroLaiOver.png",
				onRelease = function(event)
					--xoa giao dien thong bao
					cleanGroups(groupQuestionStart, 0)
					
					--Tro ve man hinh truoc
					timer.performWithDelay(100, function(event)
						director:changeScene("lenduong", obj)
					end, 1)
				end
			}
			btnMenu.x = bgMessage.x -- 48
			btnMenu.y = bgMessage.y + 52
			btnMenu.isVisible = false
			groupQuestionStart:insert(btnMenu)
			
			timer.performWithDelay(1000, function(e)
				--
				btnMenu.isVisible = true
			end, 1)
		end
		--Bat phan nhac gioi thieu phan thi
		audio.play( khoidong, { channel=1, loops=0, fadein=5000, onComplete = function(event) 
			if groupQuestionStart then
				--print("Bat dau")
				timer.performWithDelay(2000, submitAccount, 1)
				--xoa giao dien thong bao
				cleanGroups(groupQuestionStart, 0)
				--dat thoi gian phan thi la 60 giay
				times = 60
				--bat dau tinh thoi gian phan thi
				timer.performWithDelay(1000, begin, 61)
				
				quesAnswer = 1
				showQuestions(dataKhoiDong[quesAnswer].questions, dataKhoiDong[quesAnswer].answers, dataKhoiDong[quesAnswer].answerAB)
				
				--Hien thi diem so dau tien
				showScore()
			end
		end})
	end
	---------------------------------------------
	--init screen
	---------------------------------------------
	function drawScreen()
		
		bg = display.newImageRect("images/bgthikhoidong.png", display.contentWidth, display.contentHeight)
		bg.x = display.contentWidth/2
		bg.y = display.contentHeight/2
		groupKhoiDong:insert(bg)

		dispayAccont()
		
		start()
	end
	
	drawScreen()
	---------------------------------------------
	--xoa du lieu
	---------------------------------------------
	function cleanGroups (curGroup, level)
		if curGroup.numChildren then
			while curGroup.numChildren > 0 do
				cleanGroups (curGroup[curGroup.numChildren], level+1)
			end
			if level > 0 then
				curGroup:removeSelf()
				curGroup = nil
			end
		else
			curGroup:removeSelf()
			curGroup = nil
			return
		end
	end
	
	unloadMe = function()
		audio.stop()
	end
	return groupKhoiDong
end